from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from unfold.admin import ModelAdmin

from notebook.models import Category, Notebook, Relationship


class RelationshipInline(admin.TabularInline):  # 或者 StackedInline
    model = Relationship
    extra = 1  # 额外空行数
    autocomplete_fields = ["notebook"]  # 如果 Notebook 数量很多，可以用自动完成搜索


@admin.register(Notebook)
# 等价于 admin.site.register(Notebook, NotebookAdmin)
class NotebookAdmin(ModelAdmin):
    # 控制在后台列表显示的列
    list_display = ("title", "state", "user", "created_time", "updated_time")
    # 在右侧显示 过滤器，管理员可以通过状态、用户来快速筛选
    list_filter = ("state", "user")
    # 在后台列表的搜索框里输入关键字时，会在 title 和 content 字段中模糊匹配
    search_fields = ("title", "content")

    # 控制后台 编辑页面 的布局
    # 二元元组的列表，[0]是标题，[1]展示了每一项都有什么内容
    fieldsets = [
        (None, {"fields": ["content"]}),
        (_("Basic Informations"), {"fields": ["title", "state", "user"]}),
    ]


@admin.register(Category)
class CategoryAdmin(ModelAdmin):
    list_display = ("name", "slug", "description")
    search_fields = ("name", "slug")
    prepopulated_fields = {"slug": ("name",)}
    inlines = [RelationshipInline]


@admin.register(Relationship)
class RelationshipAdmin(ModelAdmin):
    list_display = ("notebook", "category")
    list_filter = ("category", "notebook")
    search_fields = ("notebook__title", "category__name")
